<?php

class Nld_Gird
{
	static function select($request, $select)
	{
		if(!is_null($select)) 
		{
			////////////// Search
			if(is_array(@$request['sc']))
			foreach(@$request['sc'] as $k => $v)
			if(!empty($v['val']) && !empty($v['ext']) )
			{
				$k 	 = strpos($k,'|')?substr($k,0,-2):$k;
				$ext = explode('|',$v['ext']);
				$val = str_replace('?', $v['val'], $ext[2]);
				$val = empty($v['dbe'])?$val:new Zend_Db_Expr($val);
				if(empty($v['grp']))
				{
					if($ext[0]=='OR')
					{
						if(empty($val))
						$select->orWhere($k.' '.$ext[1]);
						else
						$select->orWhere($k.' '.$ext[1].' ? ', $val);
					}
					else
					{
						if(empty($val))
						$select->where($k.' '.$ext[1]);
						else
						$select->where($k.' '.$ext[1].' ? ', $val);
					}
				}
				else
				{
					if(!empty($val))
					$group[$k][] = Nld_Models::quoteInto((($ext[0]=='OR')?'OR':'AND')." $k ".$ext[1]." ?", $val);
					else
					$group[$k][] = (($ext[0]=='OR')?'OR':'AND')." $k ".$ext[1];
				}
				/*
				if($ext[0]=='OR')
					$select->orWhere($k.' '.$ext[1].' ? ', str_replace('?', $v['val'], $ext[2]));
				else
					$select->where($k.' '.$ext[1].' ? ', str_replace('?', $v['val'], $ext[2]));
				*/
			}
			if(!empty($group))
			foreach($group as $v)
			if(!empty($v))
			{
				$select->where(substr(implode(' ',$v),3));
			}
			
			////////////// Sort
			$sort = @$request['sort'];
			if(is_array(@$sort['k']))
			foreach($sort['k'] as $i => $k)
			{
				$select->order("$k ".@$sort['d'][$i]);
			}
		}
		return $select;
	}
	
	static function result($request, $select, $dfSort = '', $result = array())
	{
		$message = Zend_Controller_Action_HelperBroker::getStaticHelper('FlashMessenger');
		
		if(!is_null($select)) 
		{
			$select	 = self::select($request, $select);
			////////////// Get Total
			$iTotalRecords 	= Nld_Models::select()
				->from(array('aa' => new Zend_Db_Expr('('.$select.')')), 'COUNT(*) AS t')
				->query()->fetchObject()->t;
			empty($dfSort) or $select->order($dfSort);
			////////////// Limit
			if(intval(@$request['iDisplayLength'])!==0)
			$select->limit($request['iDisplayLength'], intval(@$request['iDisplayStart']));
			////////////// Get Data
			$aaData = $select->query()->fetchAll();
		}
		
		$result["group"] = @$group;
		$result["select"] = @$select.'';
		$result["sEcho"] = @$request['sEcho'];
		$result["aaData"] = @array_merge(
			is_array(@$result["aaData"])?$result["aaData"]:array(),
			@$aaData);
		$result["iTotalRecords"] = intval(@$iTotalRecords);
		$result["iTotalDisplayRecords"] = intval(@$iTotalRecords);
		$result['message'] = @array_merge(
			is_array(@$result["message"])?$result["message"]:array(), 
			$message->getMessages(), 
			$message->getCurrentMessages());
		
		$message->clearMessages();
		$message->clearCurrentMessages();
		return $result;
	}
}